'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { authApi, WechatLoginResponse, SmsLoginResponse, LoginResponse } from '@/apis/auth';
import { UserInfo as ApiUserInfo, UserRole, UserStatus } from '@/types/user';

interface UserInfo {
  id: string;
  username: string;
  name: string;
  role: UserRole;
  avatar?: string;
  phone?: string;
  openid?: string;
}

interface AuthContextType {
  isAuthenticated: boolean;
  userInfo: UserInfo | null;
  login: (username: string, password: string) => Promise<boolean>;
  wechatLogin: (openid: string) => Promise<WechatLoginResponse>;
  smsLogin: (phone: string, code: string) => Promise<SmsLoginResponse>;
  bindPhone: (phone: string, code: string, openid: string) => Promise<boolean>;
  bindWechat: (userId: string, openid: string) => Promise<boolean>;
  logout: () => void;
  loading: boolean;
  token: string | null;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: React.ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const pathname = usePathname();

  // 转换 API UserInfo 到本地 UserInfo
  const convertApiUserToLocal = (apiUser: ApiUserInfo): UserInfo => {
    return {
      id: apiUser.id,
      username: apiUser.username,
      name: apiUser.realName || apiUser.username,
      role: apiUser.role,
      avatar: undefined,
      phone: apiUser.phone,
    };
  };

  useEffect(() => {
    // 检查本地存储的token和用户信息
    const savedToken = localStorage.getItem('token');
    const savedUserInfo = localStorage.getItem('userInfo');
    
    if (savedToken && savedUserInfo) {
      try {
        const user = JSON.parse(savedUserInfo);
        setUserInfo(user);
        setToken(savedToken);
        setIsAuthenticated(true);
      } catch {
        // 如果解析失败，清除无效数据
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('refreshToken');
      }
    }
    
    setLoading(false);
  }, []);

  useEffect(() => {
    // 如果未登录且不在登录页面，跳转到登录页
    if (!loading && !isAuthenticated && pathname !== '/login') {
      router.replace('/login');
    }
    // 如果已登录且在登录页面，跳转到主页
    else if (!loading && isAuthenticated && pathname === '/login') {
      router.replace('/instruments');
    }
  }, [isAuthenticated, loading, pathname, router]);

  // 保存登录信息到本地存储和状态
  const saveAuthData = (loginResponse: LoginResponse) => {
    const { token: newToken, refreshToken, user } = loginResponse;
    const localUser = convertApiUserToLocal(user);
    
    // 保存到本地存储
    localStorage.setItem('token', newToken);
    localStorage.setItem('refreshToken', refreshToken);
    localStorage.setItem('userInfo', JSON.stringify(localUser));
    
    // 更新状态
    setToken(newToken);
    setUserInfo(localUser);
    setIsAuthenticated(true);
  };

  // 传统用户名密码登录
  const login = async (username: string, password: string): Promise<boolean> => {
    try {
      // 调用真实API - 使用手机号和验证码登录
      const smsResponse = await authApi.smsLogin({ mobile: username, code: password });
      
      if (smsResponse && smsResponse.accessToken) {
        // 将SmsLoginResponse转换为LoginResponse格式
        const loginResponse: LoginResponse = {
          token: smsResponse.accessToken,
          refreshToken: smsResponse.accessToken, // 使用同一个token作为refresh token
          user: {
            id: smsResponse.userId,
            username: smsResponse.name,
            phone: smsResponse.phoneNumber,
            email: '',
            realName: smsResponse.name,
            role: UserRole.LEVEL_1_USER, // 默认角色
            status: smsResponse.status === 1 ? UserStatus.NORMAL : UserStatus.DISABLED,
            balance: 0,
            isVerified: true,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          }
        };
        
        saveAuthData(loginResponse);
        return true;
      }
      return false;
    } catch (error) {
      console.error('登录失败:', error);
      
      // 如果API调用失败，使用模拟登录作为fallback
      const validCredentials = [
        { username: 'admin', password: 'admin123', name: '系统管理员', role: 'admin' },
        { username: 'manager', password: 'manager123', name: '店长', role: 'manager' },
        { username: 'staff', password: 'staff123', name: '员工', role: 'staff' },
      ];

      const user = validCredentials.find(
        cred => cred.username === username && cred.password === password
      );

             if (user) {
         const mockApiUser: ApiUserInfo = {
           id: `user_${Date.now()}`,
           username: user.username,
           phone: '',
           email: '',
           realName: user.name,
           role: UserRole.SUPER_ADMIN,
           status: UserStatus.NORMAL,
           balance: 0,
           isVerified: false,
           createdAt: new Date().toISOString(),
           updatedAt: new Date().toISOString(),
         };
         
         const mockLoginResponse: LoginResponse = {
           token: `mock_token_${Date.now()}`,
           refreshToken: `mock_refresh_${Date.now()}`,
           user: mockApiUser
         };
        
        saveAuthData(mockLoginResponse);
        return true;
      }
      
      return false;
    }
  };

  // 微信登录
  const wechatLogin = async (openid: string): Promise<WechatLoginResponse> => {
    try {
      // 调用真实API
      const wechatResponse = await authApi.wechatLogin(openid);
      
      if (wechatResponse) {
        const { isFirstLogin, token: newToken, user } = wechatResponse;
        
        if (!isFirstLogin && newToken && user) {
          // 非首次登录，直接登录成功
          const loginResponse: LoginResponse = {
            token: newToken,
            refreshToken: `refresh_${newToken}`,
            user
          };
          saveAuthData(loginResponse);
        }
        
        return wechatResponse;
      }
      
      throw new Error('微信登录失败');
    } catch (error) {
      console.error('微信登录失败:', error);
      
      // 模拟微信登录响应
      return {
        isFirstLogin: true,
        tempUserInfo: {
          openid,
          nickname: '微信用户',
          avatar: '/default-avatar.png'
        }
      };
    }
  };

    // 短信登录
  const smsLogin = async (phone: string, code: string): Promise<SmsLoginResponse> => {
    try {
      // 调用真实API
      const smsResponse = await authApi.smsLogin({ mobile: phone, code });
      console.log(smsResponse);
      
      if (smsResponse && smsResponse.accessToken) {
        // 直接登录成功，转换为标准格式
        const loginResponse: LoginResponse = {
          token: smsResponse.accessToken,
          refreshToken: smsResponse.accessToken,
          user: {
            id: smsResponse.userId,
            username: smsResponse.name,
            phone: smsResponse.phoneNumber,
            email: '',
            realName: smsResponse.name,
            role: UserRole.LEVEL_1_USER,
            status: smsResponse.status === 1 ? UserStatus.NORMAL : UserStatus.DISABLED,
            balance: 0,
            isVerified: true,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          }
        };
        saveAuthData(loginResponse);
        
        // 返回兼容的响应格式
        return {
          accessToken: smsResponse.accessToken,
          source: smsResponse.source,
          userId: smsResponse.userId,
          userRoleType: smsResponse.userRoleType,
          teamId: smsResponse.teamId,
          identityAuthenticationId: smsResponse.identityAuthenticationId,
          shippingAddressId: smsResponse.shippingAddressId,
          name: smsResponse.name,
          phoneNumber: smsResponse.phoneNumber,
          identityType: smsResponse.identityType,
          area: smsResponse.area,
          researchDirection: smsResponse.researchDirection,
          affiliatedInstitution: smsResponse.affiliatedInstitution,
          unit: smsResponse.unit,
          position: smsResponse.position,
          status: smsResponse.status,
        };
      }
      
      throw new Error('短信登录失败');
    } catch (error) {
      console.error('短信登录失败:', error);
      
      // 模拟短信登录响应 - 返回SmsLoginResponse格式
      return {
        accessToken: `mock_token_${Date.now()}`,
        source: 'admin',
        userId: `user_${Date.now()}`,
        userRoleType: null,
        teamId: null,
        identityAuthenticationId: null,
        shippingAddressId: null,
        name: '测试用户',
        phoneNumber: phone,
        identityType: '',
        area: '',
        researchDirection: '',
        affiliatedInstitution: '',
        unit: '',
        position: '',
        status: 1,
      };
    }
  };

  // 绑定手机号
  const bindPhone = async (phone: string, code: string, openid: string): Promise<boolean> => {
    try {
      // 调用真实API
      const loginResponse = await authApi.bindPhone({ phone, code, openid });
      
      if (loginResponse) {
        saveAuthData(loginResponse);
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('绑定手机号失败:', error);
      
      // 模拟绑定成功
      const mockApiUser: ApiUserInfo = {
        id: `user_${Date.now()}`,
        username: phone,
        phone,
        email: '',
        realName: '微信用户',
        role: UserRole.LEVEL_1_USER,
        status: UserStatus.NORMAL,
        balance: 0,
        isVerified: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      
      const mockLoginResponse: LoginResponse = {
        token: `bound_token_${Date.now()}`,
        refreshToken: `bound_refresh_${Date.now()}`,
        user: mockApiUser
      };
      
      saveAuthData(mockLoginResponse);
      return true;
    }
  };

  // 绑定微信
  const bindWechat = async (userId: string, openid: string): Promise<boolean> => {
    try {
      // 调用真实API
      const loginResponse = await authApi.bindWechat({ userId, openid });
      
      if (loginResponse) {
        saveAuthData(loginResponse);
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('绑定微信失败:', error);
      
      // 模拟绑定成功
      const mockApiUser: ApiUserInfo = {
        id: userId,
        username: `user_${userId}`,
        phone: '',
        email: '',
        realName: '手机用户',
        role: UserRole.LEVEL_1_USER,
        status: UserStatus.NORMAL,
        balance: 0,
        isVerified: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      
      const mockLoginResponse: LoginResponse = {
        token: `bound_token_${Date.now()}`,
        refreshToken: `bound_refresh_${Date.now()}`,
        user: mockApiUser
      };
      
      saveAuthData(mockLoginResponse);
      return true;
    }
  };

  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('userInfo');
    setUserInfo(null);
    setToken(null);
    setIsAuthenticated(false);
    router.push('/login');
  };

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        userInfo,
        login,
        wechatLogin,
        smsLogin,
        bindPhone,
        bindWechat,
        logout,
        loading,
        token,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}; 